<?php

!defined('BASE_PATH')&&die('forbidden');

class core{
	
	private static $debug = 0;
	
	private static $class_map = array();
	
	public static function add_class_map($old_classname,$new_classname){
		
		self::$class_map[$old_classname] = $new_classname;
		
	}
	
	public static function del_class_map($classname){
		
		if (isset(self::$class_map[$classname])) {
			
			unset(self::$class_map[$classname]);
			
		}
		
	}
	
	public static function &factory($classname, $args = array()){
		
		if (isset(self::$class_map[$classname])) {
			
			$classname = self::$class_map[$classname];
			
		}
		
		return self::load($classname, $args);
		
	}
	
	public static function &f($classname, $args = array()){
		
		if (isset(self::$class_map[$classname])) {
			
			$classname = self::$class_map[$classname];
			
		}
		
		return self::load($classname, $args);
		
	}
	
	public static function &load($classname, $args = array()){
		
		$args_md5_string = md5(implode('-', $args));
		
		if (!isset($GLOBALS['_OBJS'][$classname][$args_md5_string])) {
			
			if (!class_exists($classname)) {
				
				include(self::parse_class_path($classname));

			}
			
			$_ro = new ReflectionClass($classname);
			$GLOBALS['_OBJS'][$classname][$args_md5_string] = $_ro->newInstanceArgs($args);
			
		}
		
		return $GLOBALS['_OBJS'][$classname][$args_md5_string];
		
	}
	
	public static function parse_class_path($classname){
		
		return BASE_PATH . strtr($classname,'_','/') . '.class.php';
		
	}
	
	public static function &router(){
		
		return self::factory('core_route_router');
		
	}
	
	public static function &action($actionname){
		
		$actionname = 'action_' . $actionname;
		
		if (!file_exists(core::parse_class_path($actionname))) {
			self::exit_404('action is not exist.');
		}
		
		return self::factory($actionname);
		
	}
	
	public static function &view(){
		
		return self::factory('core_view');
		
	}
	
	public static function &model(){
		
		return self::factory('core_model');
		
	}
	
	public static function &db(){
		
		return self::factory('core_db_comm');
		
	}
	
	public static function &session(){
		
		return self::factory('core_session_comm');
		
	}
	
	public static function &sign(){
		
		return self::factory('core_auth_sign');
		
	}
	
	public static function &cache(){
		
		return self::factory('core_cache_secache');
		
	}
	
	public static function exit_404($msg = ''){
		$output = '<center style="width:350px;margin:100px auto;font-family:courier new">404 : Sorry, not found! <a href="javascript:history.go(-1);">Go back</a></center>';
		if (self::$debug) {
			$output = $msg;
		}
		die($output);
	}
}



require(BASE_PATH.'config/classmap.config.php');
foreach($CLASS_MAPS as $old_class=>$new_class){
	core::add_class_map($old_class,$new_class);
}
unset($CLASS_MAPS);